# _*_ coding: utf-8 _*_
# @Time : 2021/10/11 16:05
# @Author : Mr.C
# @File : 简单线性回归(sklearn).py
# @Project : ML_algorithm

# 引入依赖
import numpy as np
import matplotlib.pyplot as plt

# 0.导入数据
points = np.genfromtxt("data.csv", delimiter=",")

# 提取points中的两列数据,作为x,y
x = points[:, 0]
y = points[:, 1]

# 1.用plt画出散点图
# plt.scatter(x,y)
# plt.show()

# 2.定义损失函数,损失函数是系数的函数，另外还要传入数据的x,y
def compute_cost(w, b, points):
    total_cost = 0
    M = len(points)

    # 逐点计算平方损失误差，然后求平均数
    for i in range(M):
        x = points[i, 0]
        y = points[i, 1]
        total_cost += (y - w * x - b) ** 2

    return total_cost/M

from sklearn.linear_model import LinearRegression
lr = LinearRegression()

x_new = x.reshape(-1, 1) # 转为二维，方便矩阵操作
y_new = y.reshape(-1, 1)

lr.fit(x_new, y_new)
# 从训练好的模型中提取系数和截距
w = lr.coef_[0, 0]
b = lr.intercept_[0]
print("w is:", w)
print("b is:", b)

cost = compute_cost(w, b, points)
print("cost is:", cost)

# 画出拟合曲线
plt.scatter(x, y)
# 针对每一个x，计算预测值
pred_y = w * x + b

plt.plot(x, pred_y, c="r")
plt.show()